﻿using System;
using System.ComponentModel;
using System.Windows.Navigation;
using GalaSoft.MvvmLight;
using Microsoft.Practices.ServiceLocation;

namespace DotNet.Phone8.MvvmLight.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public class ViewModelBaseExtra : ViewModelBase
    {
        protected INavigateService NavigationService { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public ViewModelBaseExtra()
            : base()
        {
            //ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
            this.NavigationService = ServiceLocator.Current.GetInstance<INavigateService>();

            this.NavigationService.Navigated += navigationService_Navigated;
            this.NavigationService.BackKeyPress += navigationService_BackKeyPress;
        }

        void navigationService_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (NavigationService.RootFrame == null)
            {
                return;
            }

            Type viewType = NavigationService.RootFrame.Content.GetType();
            if (NavigationService.GetViewType(this.GetType()) != viewType)
            {
                return;
            }

            OnBackPress(sender, e);
        }

        void navigationService_Navigated(object sender, NavigationEventArgs e)
        {
            if (e.Content == null)
            {
                return;
            }

            if (NavigationService.GetViewType(this.GetType()) != e.Content.GetType())
            {
                return;
            }

            NavigationParamsEventArgs ep = new NavigationParamsEventArgs(NavigationService.NavigationUri, e.NavigationMode);

            OnNavigated(sender, ep);
        }

        protected virtual void OnNavigated(object sender, NavigationParamsEventArgs e)
        {

        }

        protected virtual void OnBackPress(object sender, CancelEventArgs e)
        {

        }
    }
}
